import React, { useEffect, useRef, useState } from 'react';
import { Pie, G2 } from '@antv/g2plot';
import { GetG2list } from '../../../../api/api.js';

const G = G2.getEngine('canvas');

function Room_T1() {
    const chartRef = useRef(null);
    const [data, setData] = useState([]);

    useEffect(() => {
        const fetchData = async () => {
            try {
                const response = await GetG2list();
                const responseData = response.data.data;
                setData(responseData);
            } catch (error) {
                console.error('Error fetching data:', error);
            }
        };

        fetchData();
    }, []);

    useEffect(() => {
        if (data.length > 0) {
            const cfg = {
                appendPadding: 10,
                data: data,
                angleField: 'specsum',
                colorField: 'buildName',
                radius: 0.75,
                legend: false,
                label: {
                    type: 'spider',
                    labelHeight: 40,
                    formatter: (data, mappingData) => {
                        const group = new G.Group({});
                        group.addShape({
                            type: 'circle',
                            attrs: {
                                x: 0,
                                y: 0,
                                width: 40,
                                height: 50,
                                r: 5,
                                fill: mappingData.color,
                            },
                        });
                        group.addShape({
                            type: 'text',
                            attrs: {
                                x: 10,
                                y: 8,
                                text: `${data.buildName}`,
                                fill: mappingData.color,
                            },
                        });
                        group.addShape({
                            type: 'text',
                            attrs: {
                                x: 0,
                                y: 25,
                                text: `${data.cout}人 ${data.odds}%`,
                                fill: 'rgba(0, 0, 0, 0.65)',
                                fontWeight: 700,
                            },
                        });
                        return group;
                    },
                },
                interactions: [{ type: 'element-selected' }, { type: 'element-active' }],
            };

            const piePlot = new Pie(chartRef.current, cfg);
            piePlot.render();

            return () => {
                piePlot.destroy();
            };
        }
    }, [data]);

    return <div style={{ width: '100%' }} ref={chartRef}></div>;
}

export default Room_T1;
